<template>
  <div class="warpper">
    <div class="refuel-log">
      <p class="title">
        <span class="license">{{ $store.state.user.license }}</span
        ><b style="font-size: 14px; font-family: 'Gill Sans'; color: #999">
          ({{ $store.state.user.carType }})</b
        >
        <i
          class="el-icon-search"
          style="font-size: 15px; cursor: pointer"
          @click="startSearch"
        ></i>
        <i
          v-if="payMoney || payMoneyLow || stationIds.length > 0"
          title="重置"
          class="el-icon-brush"
          style="font-size: 16px; cursor: pointer; transform: rotate(180deg)"
          @click="refresh"
        ></i>
        <span class="tip" @click="seeDetail"
          >总计<b>{{ $store.state.user.payTotal.toFixed(2) || 0 }}</b>
          元，总里程：<b
            >{{ $store.state.user.mileage }}公里&nbsp;&nbsp;({{
              avgOil
            }}L/百公里)</b
          ></span
        >
        <el-button
          type="primary"
          size="small"
          icon="el-icon-circle-plus"
          @click="add"
          style="float: right; margin: 8px 20px 0 0"
          >新增
        </el-button>
        <el-button
          type="primary"
          size="small"
          icon="el-icon-download"
          @click="exportExcel"
          style="float: right; margin: 8px 20px 0 0"
          >导出
        </el-button>
      </p>
      <el-button
        type="primary"
        v-if="false"
        size="default"
        @click="switchTabdledoLayout"
        >切换</el-button
      >

      <template>
        <el-table
          ref="table1"
          v-show="!switchtable"
          :data="refuelLog"
          v-sticky-header
          border
        >
          <el-table-column label="日期" width="150">
            <template slot-scope="scope">
              {{ scope.row.refuel_time | timeFormate("YYYY-MM-DD") }}
            </template>
          </el-table-column>
          <el-table-column prop="pay_money" label="金额（元）" width="150">
          </el-table-column>
          <el-table-column label="支付方式" width="150">
            <template slot-scope="scope">
              {{ scope.row.pay_type | payType }}
            </template>
          </el-table-column>
          <el-table-column prop="oil_type" label="油号"> </el-table-column>
          <el-table-column prop="liters" label="升" width="150">
          </el-table-column>
          <el-table-column
            prop="station_name"
            align="left"
            label="加油站"
            width="150"
          >
          </el-table-column>
          <el-table-column
            prop="station_address"
            label="地址"
            width="150"
            align="left"
          >
          </el-table-column>
          <!-- <el-table-column prop="mileage" label="里程" align="left">
          </el-table-column>
          <el-table-column label="平均油耗" align="left">
            <template slot-scope="scope">
              {{ scope.row.avg_kilo || "--" }}L/百公里
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            width="120"
            fixed="right"
            align="center"
          >
            <template slot-scope="scope">
              <el-button-group>
                <el-button
                  type="primary"
                  size="small"
                  @click="edit(scope.row, scope.$index)"
                  icon="el-icon-edit"
                ></el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="del(scope.row)"
                  icon="el-icon-delete"
                ></el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-show="!switchtable"
          style="float: right; margin-top: 10px"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </template>
      <template>
        <el-table
          v-show="switchtable"
          v-sticky-header
          :data="tableData"
          style="width: 100%"
        >
          <el-table-column prop="date" label="日期" width="480">
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="480">
          </el-table-column>
          <el-table-column
            prop="address"
            label="地址"
            width="480"
            fixed="right"
          >
          </el-table-column>
        </el-table>
      </template>
    </div>
    <el-dialog title="提示" :visible.sync="delConfirm" width="30%" center>
      <span style="color: red"
        >是否删除{{
          refuelObj.refuel_time | timeFormate("YYYY-MM-DD")
        }}日的加油记录？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="delConfirm = false">取 消</el-button>
        <el-button type="danger" @click="delConfirmSubmit()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="查询"
      :visible.sync="search"
      top="4vh"
      @close="closeSearch"
    >
      <el-input
        v-model="payMoney"
        placeholder="加油金额大于此"
        clearable
      ></el-input>
      <el-input
        style="margin-top: 22px"
        v-model="payMoneyLow"
        placeholder="加油金额小于此"
        clearable
      ></el-input>
      <el-select
        v-model="stationIds"
        value-key=""
        placeholder="加油站"
        clearable
        filterable
        multiple
        style="margin-top: 22px; width: 100%"
      >
        <el-option
          v-for="item in stations"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeSearch">取 消</el-button>
        <el-button type="primary" @click="serach">查 询</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="addorEdit == 'add' ? '新增记录' : '编辑记录'"
      :visible.sync="addOne"
      top="4vh"
      @close="close"
    >
      <el-form :model="form" ref="addOneForm" :rules="rules">
        <el-form-item
          label="加油日期："
          :label-width="formLabelWidth"
          prop="refuel_time"
        >
          <el-date-picker
            v-model="form.refuel_time"
            type="date"
            placeholder="选择日期："
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="付款金额："
          :label-width="formLabelWidth"
          prop="pay_money"
        >
          <el-input-number
            v-model="form.pay_money"
            :precision="2"
            :step="0.1"
            :max="100000"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="付款方式："
          :label-width="formLabelWidth"
          prop="pay_type"
        >
          <el-select v-model="form.pay_type" placeholder="请选付款方式">
            <el-option label="现金" value="cash"></el-option>
            <el-option label="微信" value="wechat"></el-option>
            <el-option label="支付宝" value="alipay"></el-option>
            <el-option label="银行卡" value="card"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="油号："
          :label-width="formLabelWidth"
          prop="oil_type"
        >
          <el-radio v-model="form.oil_type" label="92">92</el-radio>
          <el-radio v-model="form.oil_type" label="95">95</el-radio>
          <el-radio v-model="form.oil_type" label="98">98</el-radio>
          <el-radio v-model="form.oil_type" label="100">100</el-radio>
        </el-form-item>
        <el-form-item label="升：" :label-width="formLabelWidth" prop="liters">
          <el-input-number
            v-model="form.liters"
            :precision="2"
            :step="0.1"
            :max="100000"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          label="加油站："
          :label-width="formLabelWidth"
          prop="refuel_station_id"
        >
          <el-select v-model="form.refuel_station_id" placeholder="请选加油站">
            <el-option
              v-for="item in stations"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="里程："
          :label-width="formLabelWidth"
          prop="mileage"
        >
          <el-input-number
            v-model="form.mileage"
            :precision="1"
            :step="100"
            :max="10000000"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="照片：" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="headers"
            :with-credentials="true"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addOne = false">取 消</el-button>
        <el-button
          v-if="addorEdit == 'add'"
          type="primary"
          @click="addSubmit"
          v-loading="loading"
          >新 增</el-button
        >
        <el-button v-if="addorEdit == 'edit'" type="primary" @click="editSubmit"
          >保 存</el-button
        >
      </div>
    </el-dialog>
    <detail :visible="visible" @close="closeDetail"></detail>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  getRefuelLogAll,
  delRefuelLogById,
  getStationAll,
  newRefuelLog,
  updateRefuelLogById,
  getLoginUserInfo,
  downLoadExcel,
  getAntiWeightToken,
  getAvgOil
} from "@http/api.js";
import * as types from "../store/type";
import axios from "axios";
import { lsRead } from "@/common/js/ls.js";
import detail from './detail.vue'
export default {
  components: {
    detail,
  },
  data() {
    var checkZero = (rule, value, callback) => {
        if (value === 0) {
          callback(new Error('必须大于0'));
        } else{
          callback();
        }
    };
    return {
      tableData: [{
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1518 弄'
          }, {
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1517 弄'
          }, {
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1516 弄'
          },{
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1518 弄'
          }, {
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1517 弄'
          }, {
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1516 弄'
          },{
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1518 弄'
          }, {
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1517 弄'
          }, {
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1516 弄'
          },{
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1518 弄'
          }, {
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1517 弄'
          }, {
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1516 弄'
          },{
            date: '2016-05-02',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1518 弄'
          }, {
            date: '2016-05-04',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1517 弄'
          }, {
            date: '2016-05-01',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1519 弄'
          }, {
            date: '2016-05-03',
            name: '王小虎',
            address: '上海市普陀区金沙江路 1516 弄'
          }],
      switchtable:false,
      currentTime:"",
      loading: false,
      visible: false,
      search: false,
      payMoney: "",
      payMoneyLow: "",
      stationIds: [],
      antiWeightToken: "",
      imageUrl: "",
      uploadUrl: "",
      pageNum: 1,
      pageSize: 10,
      count: 0,
      sum: 0,
      addorEdit: "add",
      delConfirm: false,
      addOne: false,
      refuelLog: [],
      refuelObj: {},
      formLabelWidth: "120px",
      form: {
        refuel_time: "",
        pay_money: 0,
        pay_type: "",
        oil_type: "92",
        liters: "",
        refuel_station_id: "",
        mileage: "",
        photo: "",
      },
      stations: [],
      headers: {
        Authorization: lsRead("token"),
      },
      avgOil: 0,
      rules: {
        refuel_time: [
            { required: true, message: '请输入日期', trigger: 'change' },
          ],
          pay_money: [
            { required: true,validator: checkZero, trigger: 'blur' }
          ],
          pay_type: [
            { required: true, message: '请选择付款方式', trigger: 'change' }
          ],
          liters: [
          { required: true,validator: checkZero, trigger: 'blur' }
          ],
          refuel_station_id: [
            { required: true, message: '请选择加油站', trigger: 'change' }
          ],
          mileage: [
          { required: true,validator: checkZero, trigger: 'blur' }
          ]
        }
    };
  },
  computed: {},
  mounted() {
    this._getRefuelLogAll();
    this._getStationAll();
    this._getAvgOil();
    this.$store.commit(types.LOGIN, lsRead("user"));
    this.uploadUrl = axios.defaults.baseURL + "/refuel/photo";
  },
  methods: {
    switchTabdledoLayout(){
      this.switchtable = !this.switchtable
      // window.history.go(0)
    },
    closeDetail() {
      this.visible = false;
    },
    seeDetail() {
      this.visible = true;
    },
    refresh() {
      this.payMoney = "";
      this.payMoneyLow = "";
      this.stationIds = [];
      this.serach();
    },
    _getAvgOil() {
      getAvgOil().then(res => {
        this.avgOil = res.data.data || 0;
      })
    },
    startSearch() {
      this.search = true;
    },

    serach() {
      this.pageNum = 1;
      this._getRefuelLogAll();
      this.closeSearch();
    },

    closeSearch() {
      this.search = false;
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.photo = JSON.parse(file.response).data;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isLt2M;
    },
    getLoginUser() {
      let userId = lsRead("userId");
      getLoginUserInfo({ userId }).then((res) => {
        let { code, data, message } = res.data;
        if (code == 200) {
          this.$store.commit(types.LOGIN, data);
        }
      });
    },
    addSation() {
      this.$router.push("/station");
    },
    close() {
      this.$refs["addOneForm"].resetFields();
    },
    handleCurrentChange(val) {
      this.cu
      this.pageNum = val;
      this._getRefuelLogAll(val,this.pageSize);
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this._getRefuelLogAll(this.pageNum,val);
    },
    _getStationAll() {
      getStationAll().then((res) => {
        let { code, data, message } = res.data;
        if (code == 200) {
          this.stations = data.map((st) => {
            return {
              key: st.stationId,
              value: st.stationId,
              label: st.stationName,
            };
          });
        } else {
          this.$notify({
            title: "wrong",
            message: message || "getStationAll error!",
            type: "error",
          });
        }
      });
    },
    _getRefuelLogAll(pageNum,pageSize) {
      let requestId = new Date().getTime();
      this.currentTime = requestId;
      getRefuelLogAll({ pageNum: this.pageNum, pageSize: this.pageSize, payMoney: this.payMoney, payMoneyLow: this.payMoneyLow, stationIds: this.stationIds.join(",") }).then(
        (res) => {
          let { code, data, message } = res.data;
          if (code == 200) {
            if(pageNum && pageSize && (pageNum != this.pageNum || pageSize != this.pageSize)){
              return;
            }
            if(this.currentTime != requestId){
              return;
            }
            this.refuelLog = data.list;
            this.count = Number(data.total);
          } else {
            this.$notify({
              title: "wrong",
              message: message || "getRefuelLogAll error!",
              type: "error",
            });
          }
        }
      );
    },
    edit(row, index) {
      this.addorEdit = "edit";
      this.refuelObj = row;
      this.addOne = true;
      this.$nextTick(() => {
        this.form = Object.assign({}, this.refuelLog[index]);
        this.imageUrl = row.imageUrl;
      });
    },
    editSubmit() {
      this.$refs["addOneForm"].validate((valid) => {
        if (valid) {
          updateRefuelLogById(
            Object.assign({ id: this.refuelObj.refuel_id }, this.form)
          )
            .then((res) => {
              let { code, data, message } = res.data;
              if (code == 200) {
                this._getRefuelLogAll();
                this.getLoginUser();
                this._getAvgOil();
                this.addOne = false;
              } else {
                this.$notify({
                  title: "wrong",
                  message: message || "newRefuelLog error!",
                  type: "error",
                });
              }
            })
            .catch((e) => {
              console.log(e);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    del(row) {
      this.refuelObj = row;
      this.delConfirm = true;
    },
    delConfirmSubmit() {
      delRefuelLogById({ id: this.refuelObj.refuel_id }).then((res) => {
        let { code, data, message } = res.data;
        if (code == 200) {
          this.delConfirm = false;
          this._getRefuelLogAll();
          this.getLoginUser();
          this._getAvgOil();
        } else {
          this.$notify({
            title: "wrong",
            message: message || "delRefuelLogById error!",
            type: "error",
          });
        }
      });
    },
    add() {
      this.addorEdit = "add";
      this.imageUrl = "";
      this.form.refuel_id && delete this.form.refuel_id;
      getAntiWeightToken().then(res => {
        let { code, data, message } = JSON.parse(res.data);
        if (code == 200) {
          this.antiWeightToken = data;
          this.addOne = true;
        } else {
          this.$notify({
            title: "wrong",
            message: message || "newRefuelLog error!",
            type: "error",
          });
        }
      })
    },
    addSubmit() {
      this.$refs["addOneForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          newRefuelLog(Object.assign({}, this.form), this.antiWeightToken).then((res) => {
            let { code, data, message } = res.data;
            if (code == 200) {
              this._getRefuelLogAll();
              this.getLoginUser();
              this._getAvgOil();
              this.addOne = false;
            } else if(code == 400){
              this.$message.error(JSON.parse(message).photo);

            } else {
              this.$notify({
                title: "wrong",
                message: message || "newRefuelLog error!",
                type: "error",
              });
            }
          }).catch(e => {
            this.loading = false;
          }).finally(() => {
            this.loading = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    exportExcel() {
      downLoadExcel().then((res) => {
        this.download(res);
      });
    },
    download(res) {
      const file = res.headers["content-disposition"].split(";")[1];
      const fileName = decodeURI(file.split("=")[1]);
      let a = document.createElement("a");
      let blob = new Blob([res.data], { type: "application/vnd.ms-excel" });
      let objectUrl = URL.createObjectURL(blob);
      a.setAttribute("href", objectUrl);
      a.setAttribute("download", fileName);
      a.click();
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.el-upload .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="stylus" rel="stylesheet/stylus" scoped>
.warpper
  width 100%
  .refuel-log
    width 100%
    margin 0 auto
    .title
      margin 0 0 20px 0
      text-align left
      font-size 22px
      height 30px
      font-family "'Gill Sans'"
      .license
        display inline-block
        height 30px
        line-height 30px
        text-align center
        padding 4px 10px
        margin-right 4px
        background-color #ff6e34
        border-radius 6px
        border 1px solid #ff6e34
        color #fff
      .el-icon-circle-plus
        display inline-block
        vertical-align middle
        font-size 26px
        color #409EFF
        cursor pointer
        opacity 0.8
        &:hover
          opacity 1
      .tip
        display inherit
        font-family "'Gill Sans'"
        font-size 13px
        height 30px
        line-height 50px
        float right
        color #999
        &:hover
          cursor pointer
          color #000
</style>
